<template>
  <div
    v-if="!initializing"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  >
    <span
      v-if="icon.type === 'svg' && icon.content"
      v-html="icon.content"
      class="vc-icon"
      :style="svgStyle"
    ></span>
    <img
      v-else-if="icon.type === 'base64' && icon.content"
      :src="'data:image/png;base64,' + icon.content"
      :style="base64Style"
      alt=""
    />
  </div>
</template>

<script setup>
import { computed, getCurrentInstance, inject, nextTick, onMounted, onUnmounted, ref } from 'vue';
import { getIconList } from '@/utils/system';
import visual from "@/visual/js/visual";
import EventHandler from "@/visual/js/event";

const props = defineProps({
  node: Object
});
const initializing = ref(true);
const currNode = ref(props.node);
const iconList = ref([]);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);
const icon = ref({});

const svgStyle = computed(() => {
  const compStyle = currNode.value.currCompStyle || {};
  const result = {};
  result['font-size'] = compStyle['size'] ? (compStyle['size'] + 'px') : 'inherit';
  result['color'] = compStyle['color'] || 'inherit';
  return result;
});

const base64Style = computed(() => {
  const compStyle = currNode.value.currCompStyle || {};
  const result = {};
  result['width'] = compStyle['size'] ? (compStyle['size'] + 'px') : 'inherit';
  result['height'] = compStyle['size'] ? (compStyle['size'] + 'px') : 'inherit';
  result['color'] = compStyle['color'] || 'inherit';
  return result;
});

const init = async(styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  const compStyle = currNode.value.currCompStyle || {};
  const iconId = compStyle['iconId'];
  icon.value = iconList.value.find(item => item.id === iconId) || {};
  await nextTick(() => initializing.value = false);
};
const getData = () => {
  return {};
};

const changeStyle = (styleId) => {
  init(styleId);
};

const refresh = async() => {
  initializing.value = true;
  const compStyle = currNode.value.currCompStyle || {};
  const iconId = compStyle['iconId'];
  icon.value = iconList.value.find(item => item.id === iconId) || {};
  await nextTick(() => initializing.value = false);
};

const loadData = async() => {
  iconList.value = await getIconList();
};

onMounted(async() => {
  await loadData();
  await init();
  await eventHandler.trigger('初始化事件');
});

onUnmounted(() => {
  eventHandler.unregister();
});

defineExpose({ getData, changeStyle, refresh });
</script>

<style scoped>
.vc-icon {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  font-size: inherit;
  width: 1em!important;
  height: 1em!important;
}
.vc-icon svg {
  width: 1em;
  height: 1em;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>